package com.shangcheng.service;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shangcheng.entity.TCustomer;
import com.shangcheng.mapper.TCustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class CustmerServiceImpl {
    /*application.yml中加一个自定义配置项 例如
 jwt:
   secretkey: mimi$k_#ok  */
    @Value("${jwt.secretkey}") //配置在 yml中注入进来
    private String secret;
    @Autowired
    private TCustomerMapper customerDao;
    @Transactional(readOnly = true)
    public TCustomer queryByUsername(String username) {
        QueryWrapper<TCustomer> qw = new QueryWrapper<>();
        qw.eq("user_name", username);
        return customerDao.selectOne(qw);
    }

    //创建tocken
    public String createTocken(TCustomer customer) {
        Map<String,Object> headerMap = new HashMap<>();//jwt header  hutool可省，默认值
        headerMap.put("alg","HS256");
        headerMap.put("typ","JWT");
        Map<String,Object> playLoad = new HashMap<>();//jwt payload
        playLoad.put("id",customer.getId());
        playLoad.put("username",customer.getUserName());
        playLoad.put("role","custmer");//角色 顾客
        //有效期一天
        playLoad.put("exp",String.valueOf(System.currentTimeMillis()+1000*60*60*24));//一天后过期
        // playLoad.put("exp",String.valueOf(System.currentTimeMillis()+1000*60*2));//2分钟过期
        String token =  JWTUtil.createToken(headerMap,playLoad,secret.getBytes());
        return token;
    }
}
